﻿using AutoMapper;
using Commonality.Common;
using Commonality.ReturnView;
using Commonality.ServerEnum;
using Commonality.ServerEnum.AttributeEnum;
using IService.Managemen;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Models.Managemen;
using ModelToDto.Managemen;
using Service;
using SqlSugar;
using System.Linq.Expressions;
using System.Xml.Linq;

namespace ManagementPlatform.Controllers
{
    /// <summary>
    /// 测试接口
    /// </summary>

    public class UserController : BaseController
    {
        public IUserService _userService;
        public IMapper _mapper;
        public UserController(IUserService userService, IMapper mapper)
        {

            _userService = userService;
            _mapper = mapper;
        }
        /// <summary>
        /// 用户分页
        /// </summary>
        /// <param name="searchString">查询条件</param>
        /// <param name="userType">用户类型</param>
        /// <param name="userStatu">用户状态</param>
        /// <param name="userGender">用户性别</param>
        /// <param name="url"></param>
        /// <param name="pageIndex">页数</param>
        /// <param name="pageSize">条数</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Index(string? searchString, string? userType, string? userStatu, string? userGender, string? url, int pageIndex = 1, int pageSize = 10)
        {
            //数据转换
            Seatch();
            var exp = Expressionable.Create<Mp_Users>(); //创建表达式
            exp.AndIF(!string.IsNullOrEmpty(searchString), it => it.Name.Contains(searchString))
           .AndIF(!string.IsNullOrEmpty(userType), it => it.UserType == Convert.ToInt32(userType))
           .AndIF(!string.IsNullOrEmpty(userStatu), it => it.Status == Convert.ToInt32(userStatu))
           .AndIF(!string.IsNullOrEmpty(userGender), it => it.Sex == Convert.ToInt32(userGender));
            var expToExp = exp.ToExpression();
            var pageResult = _userService.QueryPage<Mp_Users>(expToExp, pageSize, pageIndex, c => c.UserId, false);
            //automap 转化
            var autoUserInfor = _mapper.Map<PagingData<Mp_Users>, PagingData<UsersDTO>>(pageResult);
            return View(autoUserInfor);
          
        }
        private static Dictionary<string, IList<SelectListItem>> CacheList = new Dictionary<string, IList<SelectListItem>>();


        private IList<SelectListItem> GetSelectListItems(string userType, Type type)
        {
            if (CacheList.ContainsKey(userType))
            {
                return CacheList[userType];
            }
            CacheList[userType] = ReadEnumRemark.ToSelectListByEnum(type, userType);

            return CacheList[userType];
        }
        /// <summary>
        /// 用户表查询条件
        /// </summary>
        /// <returns></returns>
       // [HttpGet]
        private void Seatch()
        {
            //查询条件准备
            IList<SelectListItem> userTypeRemarkDC = GetSelectListItems("userTypeEnum", typeof( UserTypeEnum));
            IList<SelectListItem> genderTypeRemarkDC = GetSelectListItems("genderEnum", typeof(GenderEnum));
            IList<SelectListItem> statuTypeRemarkDC = GetSelectListItems("userStatuEnum", typeof(UserStatuEnum));
            //返回元组
            //var result = new Tuple<Dictionary<int, string>, Dictionary<int, string>, Dictionary<int, string>>(userTypeRemarkDC, genderTypeRemarkDC, statuTypeRemarkDC);
            ViewData["userTypeEnum"] = userTypeRemarkDC;
            ViewData["genderEnum"] = genderTypeRemarkDC;
            ViewData["userStatuEnum"] = statuTypeRemarkDC;
        }
        /// <summary>
        /// 添加用户页面视图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult AddUserView()
        {

            return View();
        }
        /// <summary>
        /// 分配角色列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task <IActionResult> AssignRoles([FromQuery]int id)
        {
           var userRoleList= await  _userService.GetUserRole(id);
     
            return View(userRoleList);
        }
        /// <summary>
        /// 设置用户角色
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task< IActionResult> AssignRolesAdd()
        {
            var requestForm = Request.Form;
            var roleList = requestForm.Where(t => t.Value[0] == "true").Select(t => t.Key.Split('_')[1]).ToList();
            
           var userId= requestForm["UserID"];
            var result= await _userService.AssignRolesAdd(Convert.ToInt32(userId), roleList);
            if (result == 1)
            {
               return RedirectToAction("Index");
            }
            else
            {
                return NotFound();
            }
            
        }
        /// <summary>
        /// 添加用户数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddUserInfo([FromBody] UsersDTO usersInfo)
        {
            if (ModelState.IsValid)
            {
                usersInfo.Password=Common.Encrypt(usersInfo.Password);
                var userEnt = _mapper.Map<UsersDTO, Mp_Users>(usersInfo);
                
                var result = await _userService.InsertAsync<Mp_Users>(userEnt);
            }

            return RedirectToAction("Index");
        }
        /// <summary>
        /// 删除用户(假删除)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> DeleteUser([FromQuery] int id)
        {

            Mp_Users Ent = new Mp_Users();
            Ent.UserId = id;
            Ent.Status = (int)UserStatuEnum.Delete;
            var upint = _userService.UpdateableFilter<Mp_Users>(Ent, x => new { x.Status }, t => t.UserId == id);
            if (upint > 0)
            {
                // new JsonResult("");
                return RedirectToAction("Index");
            }
            else
            {
                return Ok(new ErrorInfo() { Code = 601, Message = "修改失败" });
            }

        }
        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UpdateUser([FromBody] UsersDTO usersDTO)
        {

            var ent = _mapper.Map<UsersDTO, Mp_Users>(usersDTO);

            _userService.Update<Mp_Users>(ent);

            return Ok();


        }
       
    }
}
